package com.hopscotch.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.hopscotch.util.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null){
            return true;
        }else {
            response.setContentType("application/json;charset=utf-8");
            R fail = R.fail();
            fail.setMsg("请登录后重试");
            String jsonString = JSONObject.toJSONString(fail);
            PrintWriter writer = response.getWriter();
            writer.write(jsonString);
            return false;
        }
    }
}
